package com.lr.transfer.utils;

import org.apache.commons.lang3.StringUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * FileName: PdfToImageUtil
 * Author:   zhangguoqing
 * Date:     2018/9/18 17:53
 * 说明:  PDF转图片
 */
@Component
public class PdfToImageUtil {
    static Logger logger = LoggerFactory.getLogger(PdfToImageUtil.class);

    // 水印透明度
    private static float alpha = 0.2f;
    // 水印横向位置
    private static int positionWidth = 150;
    // 水印纵向位置
    private static int positionHeight = 300;
    // 水印文字字体
    private static Font font = new Font("仿宋", Font.BOLD, 26);
    // 水印文字颜色
    private static Color color = Color.GRAY;
    // 水印文字
    private static String watermark;

    //图片宽度(做成可配置项)
    private static Integer width;
    //图片高度(做成可配置项)
    private static Integer height;
    //图片格式(做成可配置项)
    private static String imgType;


    public PdfToImageUtil() {
    }

    /**
     * 有参构造,传参水印文字,生成图片时根据是否传参选择是否生成水印
     *
     * @param watermark 水印内容
     */
    public PdfToImageUtil(String watermark) {
        this.watermark = watermark;
    }

    //设置水印
    public static BufferedImage setGraphics(BufferedImage bfimage) {
        Graphics2D g = bfimage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 5、设置水印文字颜色
        g.setColor(color);
        // 6、设置水印文字Font
        g.setFont(font);
        // 7、设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        //设置旋转
        g.rotate(-Math.PI / 6);
        g.drawString(watermark, 0, (bfimage.getHeight() / 2) * 1);
        // 9、释放资源
        g.dispose();
        return bfimage;
    }

    /**
     * @author: zhangguoqing
     * @date: 2018/9/18 17:55
     * @param: [inputFile] pdf文件路径
     * @return: java.util.List<java.lang.String> 图片地址列表
     * @Description: pdf文件转图片
     */
    public static List<String> pdfToIamge(String inputFile) {
        //获取inputFile的后缀名前的内容，如："e:/test.pptx"的后缀名为："e:/test"
        String imgPath_start = inputFile.substring(0, inputFile.lastIndexOf("."));

        List<String> list=null;
        Document document = null;
        try {

            document = new Document();
            document.setFile(inputFile);
            float rotation = 0; //旋转角度
            int maxPages = document.getPageTree().getNumberOfPages();

            new ArrayList(maxPages);
            for (int i = 0; i < maxPages; i++) {
                //zoom 缩放比例 ,记住这里调清晰度,我用的是8.5超清晰,9以上就报错了
                BufferedImage bfimage = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, 2.1f);
                //设置图片的宽和高
                Image tempImage = bfimage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                BufferedImage biTemp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics gTemp = biTemp.getGraphics();
                gTemp.drawImage(tempImage, 0, 0, null);
                //加水印
                if (StringUtils.isNotBlank(watermark)) {
                    biTemp = setGraphics(biTemp);
                }
                RenderedImage rendImage = biTemp;
                //拼接图片地址
                String imgPath = imgPath_start + "_" + i + "." + imgType;
                ImageIO.write(rendImage, imgType, new File(imgPath));
                bfimage.flush();
                list.add(imgPath);
            }
        } catch (Exception e) {
            logger.error("pdf转化图片出错!", e);
        }

        if (document != null) {
            document.dispose();
        }
        return list;
    }

    @Value("${pdfToImg.imgWidth}")
    public void setWidth(Integer width) {
        PdfToImageUtil.width = width;
    }

    @Value("${pdfToImg.imgHeight}")
    public void setHeight(Integer height) {
        PdfToImageUtil.height = height;
    }

    @Value("${pdfToImg.imgType}")
    public void setImgType(String imgType) {
        PdfToImageUtil.imgType = imgType;
    }
}
